<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>CMSWing Admin</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, maximum-scale=1"
    />
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<!--    <link-->
<!--      rel="stylesheet"-->
<!--      title="default"-->
<!--      href="https://unpkg.com/amis/sdk/sdk.css"-->
<!--    />-->
<!--    <link rel="stylesheet" href="https://unpkg.com/amis/sdk/helper.css" />-->
<!--    <script src="https://unpkg.com/amis/sdk/sdk.js"></script>-->
<!--    <script src="https://unpkg.com/vue@2"></script>-->
<!--    <script src="https://unpkg.com/history@4.10.1/umd/history.js"></script>-->
    <link rel="stylesheet" title="default" href="/admin/sdk/sdk.css" />
    <link rel="stylesheet" href="/admin/sdk/helper.css" />
    <script src="/admin/sdk/sdk.js"></script>
    <script src="/admin/vue@2.js"></script>
    <script src="/admin/history.js"></script>
    <style>
      html,
      body,
      .app-wrapper {
        position: relative;
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
      .mt-0 {
        margin-top: 0 !important;
      }
      .pa-0 {
        padding: 0 !important;
      }
      .ml-2 {
        margin-left: 0.5rem !important;
      }
      .tdimg .cxd-Image-thumb {
        width: 1.7rem !important;
        height: 1.7rem !important;
      }
      .tdimg .cxd-Image--thumb {
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <div id="root" class="app-wrapper"></div>
    <script>
      (function () {
        let amis = amisRequire('amis/embed');
        const match = amisRequire('path-to-regexp').match;

        // 如果想用 browserHistory 请切换下这处代码, 其他不用变
        // const history = History.createBrowserHistory();
        const history = History.createHashHistory();

        const app = {
          type: 'app',
          brandName: 'CMSWing',
          logo: '/admin/logo.svg',
          header: {
            type: 'flex',
            justify: 'space-between',
            className: 'w-full',
            items: [
              {
                type: 'flex',
                justify: 'flex-start',
                items: [
                  {
                    type: 'button',
                    level: 'light',
                    label: 'GraphQL',
                    align: 'right',
                    icon: '/admin/graphql.svg',
                    className: 'ml-2',
                    actionType: 'drawer',
                    drawer: {
                      size: 'xl',
                      position: 'right',
                      title: 'GraphQL',
                      actions: [],
                      bodyClassName: '-m-6',
                      body: [{ type: 'iframe', src: '/graphql-dev' }],
                    },
                  },
                  {
                    type: 'button',
                    level: 'light',
                    label: 'swagger',
                    align: 'right',
                    icon: '/admin/swagger.svg',
                    className: 'ml-2',
                    actionType: 'drawer',
                    drawer: {
                      size: 'xl',
                      position: 'right',
                      title: 'Swagger',
                      actions: [],
                      bodyClassName: '-m-6',
                      body: [{ type: 'iframe', src: '/swagger-ui.html' }],
                    },
                  },
                ],
              },

              {
                type: 'flex',
                justify: 'flex-end',
                items: [
                  {
                    id: 'restart',
                    type: 'button',
                    icon: 'fa-solid fa-rotate',
                    label: '重启服务',
                    confirmText:
                      '重启服务只有在生产环境中有效，线上[模板][路由][配置][模型]修改时需要重启服务才能生效，本地开发不需要重启服务。重启大概需要1-3秒，重启时会中断服务，请在闲时使用该功能！',
                    className: 'ml-2',
                    onEvent: {
                      click: {
                        actions: [
                          {
                            componentId: 'restart',
                            actionType: 'disabled',
                          },
                          {
                            actionType: 'ajax',
                            args: {
                              api: {
                                url: '/admin/sys/server/restart',
                                method: 'get',
                              },
                              options: {
                                silent: true,
                              },
                            },
                          },
                          {
                            actionType: 'toast',
                            expression:
                              "${event.data.responseResult.responseStatus!=='yes'}",
                            args: {
                              msg: '服务重启成功！',
                            },
                          },
                          {
                            componentId: 'restart',
                            actionType: 'enabled',
                          },
                        ],
                      },
                    },
                  },
                  {
                    type: 'service',
                    api: '/admin/checkLogin',
                    body: {
                      type: 'dropdown-button',
                      label: '${adminUser.username}',
                      align: 'right',
                      icon: 'fa-regular fa-user',
                      className: 'ml-2',
                      buttons: [
                        {
                          type: 'button',
                          icon: 'fa-solid fa-power-off',
                          label: ' 退出登陆',
                          onClick: "window.localStorage.removeItem('admin_access_token'); window.location.href = '/admin/login.html';",
                          // actionType: 'url',
                          // url: '/admin/logout',
                          // blank: false,
                        },
                      ],
                    },
                  },
                ],
              },
            ],
          },
          footer: '<div class="p-2 text-center bg-light">底部区域</div>',
          // asideBefore: '<div class="p-2 text-center">菜单前面区域</div>',
          // asideAfter: '<div class="p-2 text-center">菜单后面区域</div>',
          api: '/admin/pages/admin/pages/site.json',
        };

        function normalizeLink(to, location = history.location) {
          to = to || '';

          if (to && to[0] === '#') {
            to = location.pathname + location.search + to;
          } else if (to && to[0] === '?') {
            to = location.pathname + to;
          }

          const idx = to.indexOf('?');
          const idx2 = to.indexOf('#');
          let pathname = ~idx
            ? to.substring(0, idx)
            : ~idx2
            ? to.substring(0, idx2)
            : to;
          let search = ~idx ? to.substring(idx, ~idx2 ? idx2 : undefined) : '';
          let hash = ~idx2 ? to.substring(idx2) : location.hash;

          if (!pathname) {
            pathname = location.pathname;
          } else if (pathname[0] != '/' && !/^https?\:\/\//.test(pathname)) {
            let relativeBase = location.pathname;
            const paths = relativeBase.split('/');
            paths.pop();
            let m;
            while ((m = /^\.\.?\//.exec(pathname))) {
              if (m[0] === '../') {
                paths.pop();
              }
              pathname = pathname.substring(m[0].length);
            }
            pathname = paths.concat(pathname).join('/');
          }

          return pathname + search + hash;
        }

        function isCurrentUrl(to, ctx) {
          if (!to) {
            return false;
          }
          const pathname = history.location.pathname;
          const link = normalizeLink(to, {
            ...location,
            pathname,
            hash: '',
          });

          if (!~link.indexOf('http') && ~link.indexOf(':')) {
            let strict = ctx && ctx.strict;
            return match(link, {
              decode: decodeURIComponent,
              strict: typeof strict !== 'undefined' ? strict : true,
            })(pathname);
          }

          return decodeURI(pathname) === link;
        }

        let amisInstance = amis.embed(
          '#root',
          app,
          {
            location: history.location,
          },
          {
            // watchRouteChange: fn => {
            //   return history.listen(fn);
            // },
            updateLocation: (location, replace) => {
              location = normalizeLink(location);
              if (location === 'goBack') {
                return history.goBack();
              } else if (
                (!/^https?\:\/\//.test(location) &&
                  location ===
                    history.location.pathname + history.location.search) ||
                location === history.location.href
              ) {
                // 目标地址和当前地址一样，不处理，免得重复刷新
                return;
              } else if (/^https?\:\/\//.test(location) || !history) {
                return (window.location.href = location);
              }

              history[replace ? 'replace' : 'push'](location);
            },
            jumpTo: (to, action) => {
              if (to === 'goBack') {
                return history.goBack();
              }

              to = normalizeLink(to);

              if (isCurrentUrl(to)) {
                return;
              }

              if (action && action.actionType === 'url') {
                action.blank === false
                  ? (window.location.href = to)
                  : window.open(to, '_blank');
                return;
              } else if (action && action.blank) {
                window.open(to, '_blank');
                return;
              }

              if (/^https?:\/\//.test(to)) {
                window.location.href = to;
              } else if (
                (!/^https?\:\/\//.test(to) &&
                  to === history.pathname + history.location.search) ||
                to === history.location.href
              ) {
                // do nothing
              } else {
                history.push(to);
              }
            },
            isCurrentUrl: isCurrentUrl,
            // 全局 api 请求适配器
            // 另外在 amis 配置项中的 api 也可以配置适配器，针对某个特定接口单独处理。
            requestAdaptor(api) {
              api.headers.Authorization = `Bearer ${localStorage.getItem(
                'admin_access_token',
              )}`;
              return api;
            },
            // 全局 api 适配器。
            // 另外在 amis 配置项中的 api 也可以配置适配器，针对某个特定接口单独处理。
            responseAdaptor(api, payload, query, request, response) {
              console.log(api.url);
              if (api.url === '/admin/checkLogin') {
                if (payload.statusCode === 401) {
                  response.status = 0;
                  window.location.href = '/admin/login.html';
                  return payload;
                } else if (payload.status === 0) {
                  amisInstance.updateProps({
                    data: {
                      adminUser: payload.data,
                    },
                  });
                }
              }
              return payload;
            },
            theme: 'cxd',
          },
        );

        history.listen((state) => {
          amisInstance.updateProps({
            location: state.location || state,
          });
        });
      })();
    </script>
  </body>
</html>
